#import "EaseDataBase.h"
#import "FMDatabase.h"
#import <FMDB.h>
static EaseDataBase *m1_DBCtl = nil;
@interface EaseDataBase()<NSCopying,NSMutableCopying>{
    FMDatabase  *m1_dataBase;
}
@end
@implementation EaseDataBase
-(id)copy{
    return self;
}
-(id)mutableCopy{
    return self;
}
-(id)copyWithZone:(NSZone *)zone{
    return self;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return self;
}
+(instancetype)sharedDataBase{
    if (m1_DBCtl == nil) {
        m1_DBCtl = [[EaseDataBase alloc] init];
        [m1_DBCtl initDataBase];
    }
    return m1_DBCtl;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    if (m1_DBCtl == nil) {
        m1_DBCtl = [super allocWithZone:zone];
    }
    return m1_DBCtl;
}
-(void)initDataBase{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"model.sqlite"];
    m1_dataBase = [FMDatabase databaseWithPath:filePath];
    [m1_dataBase open];
    NSString *stateSql = @"CREATE TABLE IF NOT EXISTS 'nameTable' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'messageId' VARCHAR(255),'name' VARCHAR(255),'user_avatar' VARCHAR(255),'uid' VARCHAR(255))";
    [m1_dataBase executeUpdate:stateSql];
    [m1_dataBase close];
}
- (void)addMessage:(NSString *)messageId  uid:(NSString *)uid name:(NSString *)name avatar:(NSString *)avatar{

 
    if ([self isContains:messageId]) {
        [m1_dataBase open];
        [m1_dataBase executeUpdate:@"UPDATE  nameTable SET name = ?  , user_avatar = ? , uid = ? WHERE messageId = ?",name,avatar,uid,messageId];
        [m1_dataBase close];
    }else{
        [m1_dataBase open];
        [m1_dataBase executeUpdate:@"INSERT INTO nameTable(messageId,name,user_avatar,uid)VALUES(?,?,?,?)",messageId,name,avatar,uid];
        [m1_dataBase close];
    }
}
-(void)deleteSession:(NSString *)messageId{
    [m1_dataBase open];
    [m1_dataBase executeUpdate:@"DELETE FROM nameTable WHERE  messageId = ?",messageId];
    [m1_dataBase close];
}
-(BOOL)isContains:(NSString *)messageId{
    [m1_dataBase open];
    BOOL isHave = NO;
    FMResultSet *res = [m1_dataBase executeQuery:@"SELECT * FROM nameTable WHERE  messageId = ?",messageId];
    while ([res next]) {
        isHave = YES;
    }
    [m1_dataBase close];
    return isHave;
}
-(NSDictionary *)queryWeixinWithSessionId:(NSString *)messageId{
    [m1_dataBase open];
    FMResultSet *res = [m1_dataBase executeQuery:@"SELECT * FROM nameTable WHERE messageId = ?",messageId];
    NSString *name = @"";
    NSString *uid = @"";
    NSString *avatar = @"";
    while ([res next]) {
        name = [res stringForColumn:@"name"];
        uid = [res stringForColumn:@"uid"];
        avatar = [res stringForColumn:@"user_avatar"];
    }
    [m1_dataBase close];
    return @{@"name":name,
             @"uid":uid,
             @"avatar":avatar
             };
}
@end
